package com.mzj.saas.mservice.report.service;

import cn.hutool.core.collection.CollectionUtil;
import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.community.service.AppCommunityService;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.report.vo.ReportComplainStatisticsVO;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 投诉建议统计
 */

@Service
public class ReportComplainStatisticsService {

    private static final Logger log = LoggerFactory.getLogger(ReportComplainStatisticsService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private AppCommunityService appCommunityService;

    /**
     * 列表
     * 根据不同的登录用户标签获取不同的投诉数据
     *
     * @param accessToken 验证令牌
     * @param pageNumber  起始数据
     * @param pageSize    页面大小
     * @param vo          页面数据
     * @return
     */
    public ResultBean<ApiData<ReportComplainStatisticsVO>> pages(String accessToken, Integer pageNumber, Integer pageSize, ReportComplainStatisticsVO vo) {
        log.info("ReportComplainStatisticsService  pages  accessToken ={} , vo ={} ", accessToken, vo.toString());

        /*String SQL=" SELECT s.type,SUM(s.complain_number) complain_number, SUM(s.suggest_number) suggest_number FROM saas_report_complain_statistics s inner join saas_department d on s.house_property_id=d.id  ";

        String count =" SELECT count(1) FROM saas_report_complain_statistics s  ";
        //获取登录用户信息
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        if (tokenRedisVo == null) {
            //未登录提示异常 40001 --- accessToken失效
            return ResultBean.failedResultOfToken();
        }

        //判断用户所属机构是否设置层级架构
        Long enterpriseId = tokenRedisVo.getEnterpriseId();
        DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
        if (hierarchy == null) {
            return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
        }

        //根据机构层级关系id查出企业与标签关系数据
        Long id = hierarchy.getId();
        List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
        //去重后的用户企业标签
        List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());//用户企业标签

        //1、政府机构，根据区域标签所对应区域id查
        Long areaTagId = hierarchy.getTagId();//区域标签
        Long areaId = null;
        if (enterpriseTagIds.contains(3L)) {
            areaId = hierarchy.getAreaId();//区域id
        }

        *//**
         * 根据不同标签查询不同的业务数据
         *//*
        String areaTag = "";
        if (areaTagId == 1) {
            areaTag = "province_id";
        } else if (areaTagId == 2) {
            areaTag = "city_id";
        } else if (areaTagId == 3) {
            areaTag = "district_id";
        } else if (areaTagId == 4) {
            areaTag = "street_id";
        } else if (areaTagId == 5) {
            areaTag = "community_id";
        }

        //2、物业
        Long hierarchyOrgId = null;
        if (enterpriseTagIds.contains(4L)) {
            hierarchyOrgId = hierarchy.getOrgId();
        }

        StringBuilder where = new StringBuilder(" WHERE 1=1  ");
        List<Object> args = new ArrayList<>();

        where.append(" and ( d." + areaTag + " = ? or s.house_property_id = ? ) ");
        args.add(areaId);
        args.add(hierarchyOrgId);*/
        //获取登录用户信息
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        if (tokenRedisVo == null) {
            //未登录提示异常 40001 --- accessToken失效
            return ResultBean.failedResultOfToken();
        }

        //判断用户所属机构是否设置层级架构
        Long enterpriseId = tokenRedisVo.getEnterpriseId();
        StringBuilder where = new StringBuilder();
        List<Object> args = new ArrayList<>();
        //根据企业ID查询出用户层级权限
        DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
        if (hierarchy == null) {
            return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
        }
        //获取企业用户ID
        Long id = hierarchy.getId();
        //根据企业用户ID获取公租房数据
        List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
        //获取企业标签集合
        //List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());//用户企业标签
        //判断是否是物业公司，如果不是直接返回null

        //权限过滤
        List<String> communityIds = null;
        String collect = null;
        List<Map<String, Object>> communityList = appCommunityService.findCommunity(accessToken).getResultData();
        if (CollectionUtil.isNotEmpty(communityList)) {
            communityIds = communityList.stream().map(map -> map.get("communityId")
                    .toString()).collect(Collectors.toList());
            collect = communityIds.stream().map(code -> "'" + code + "'").collect(Collectors.joining(","));
        }


        String SQL = "SELECT cs.status as status, cs.type as type, COUNT(1) as number FROM saas_complain_suggest cs " +
                " LEFT JOIN saas_house h ON cs.house_id = h.id " +
                "  WHERE h.residence_community_id in (" + collect + ")";

        if (vo != null) {

            //时间段查询
            if (StringUtils.isNotBlank(vo.getStartTime())
                    && StringUtils.isNotBlank(vo.getEndTime())) {
                String startTime = vo.getStartTime();
                String endTime = vo.getEndTime();

                where.append(" and ? <= DATE_FORMAT( cs.create_time , '%Y%m%d' )");
                where.append(" and ? >= DATE_FORMAT( cs.create_time , '%Y%m%d' )");
                args.add(startTime);
                args.add(endTime);
            }
        }

        ApiData<ReportComplainStatisticsVO> apiData = new ApiData<>();

        where.append("  GROUP BY cs.status, cs.type  ");

        //查询
        List<ReportComplainStatisticsVO> data = jdbcTemplate.query(SQL + where, new BeanPropertyRowMapper<>(ReportComplainStatisticsVO.class), args.toArray());
        List<ReportComplainStatisticsVO> reportComplainStatisticsVOList = new ArrayList<>();
        //待处理数据
        ReportComplainStatisticsVO reportComplainStatisticsVO = new ReportComplainStatisticsVO();
        reportComplainStatisticsVO.setType(1);
        reportComplainStatisticsVO.setComplainNumber(0);
        reportComplainStatisticsVO.setSuggestNumber(0);
        //已处理数据
        ReportComplainStatisticsVO reportComplainStatisticsVO1 = new ReportComplainStatisticsVO();
        reportComplainStatisticsVO1.setType(2);
        reportComplainStatisticsVO1.setComplainNumber(0);
        reportComplainStatisticsVO1.setSuggestNumber(0);
        if (CollectionUtil.isNotEmpty(data)) {
            for (ReportComplainStatisticsVO datum : data) {
                //status:处理状态：0待处理 1已处理  type:投诉类型 1投诉 2建议
                if (datum.getStatus() == 0) {
                    if (datum.getType() == 1) {
                        reportComplainStatisticsVO.setComplainNumber(datum.getNumber());
                    } else {
                        reportComplainStatisticsVO.setSuggestNumber(datum.getNumber());
                    }
                } else {
                    if (datum.getType() == 1) {
                        reportComplainStatisticsVO1.setComplainNumber(datum.getNumber());
                    } else {
                        reportComplainStatisticsVO1.setSuggestNumber(datum.getNumber());
                    }
                }
            }
        }
        reportComplainStatisticsVOList.add(reportComplainStatisticsVO);
        reportComplainStatisticsVOList.add(reportComplainStatisticsVO1);
        apiData.setData(reportComplainStatisticsVOList);

        return ResultBean.successfulResult(apiData);
    }


}
